﻿using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Ebt.Mvvm
{
    public class ControlWrapper : ControlWrapperBase<Control>
    {
    }

    public class ControlWrapperBase<TElement> : ElementWrapper<TElement> where TElement : Control
    {
        public async Task<bool> Focus()
        {
            if (SetFocus())
                return true;

            await Task.Delay(500);
            return SetFocus();
        }

        private bool SetFocus()
        {
            foreach (var control in Elements)
            {
                bool isSubtreeVisible = control.GetAscendants(true).OfType<UIElement>().All(c => c.Visibility == Visibility.Visible);

                if (isSubtreeVisible && control.Focus(FocusState.Programmatic))
                    return true;
            }
            return false;
        }
    }
}
